package eai.tp2.lpco.web.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import eai.tp2.lpco.database.DigitalCamera;
import eai.tp2.lpco.database.Order;
import eai.tp2.lpco.database.User;
import eai.tp2.lpco.purchase.IPurchase;
import eai.tp2.lpco.requests.IRequest;
import eai.tp2.lpco.web.beans.Cart;
import eai.tp2.lpco.web.beans.ErrorList;
import eai.tp2.lpco.web.beans.OrderBean;
import eai.tp2.lpco.web.beans.OrderList;
import eai.tp2.lpco.web.beans.UserBean;

/**
 * Servlet implementation class DatabaseOrder
 */
public class DatabaseOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DatabaseOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String action = request.getParameter("do");
		if(action.equals("details")) {
			int id = Integer.parseInt(request.getParameter("id"));
			IRequest req = null;
			InitialContext ctx = null;
			try {
				ctx = new InitialContext();
				req = (IRequest) ctx.lookup("RequestBean/remote");			
			} catch (NamingException e) {			
				String error;
				error = "Error while lookup for RequestBean:\n"+e.getMessage();
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}
			Order order = req.getOrder(id);
			if(order!=null) {
				OrderBean bean = new OrderBean();
				bean.setUsername(order.getUser().getUsername());
				bean.setName(order.getUser().getFullName());
				bean.setAddress(order.getUser().getAddress());
				bean.setDate(order.getDate().toString());
				bean.setAmount(order.getAmount());
				bean.setStatus(order.getStatus().toString());
				List<String> cameras = new ArrayList<String>();
				for(DigitalCamera cam: order.getDigitalCameras()) {
					cameras.add(cam.getModelName());
				}
				bean.setCameras(cameras);
				request.setAttribute("order", bean);
				RequestDispatcher rd = request.getRequestDispatcher("order_details.jsp");
				rd.forward(request, response);
			} else {
				String error;
				error = "Order with id '"+id+"' doesn't exist.";
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}
		} else if(action.equals("historic")) {
			IRequest req = null;
			InitialContext ctx = null;
			try {
				ctx = new InitialContext();
				req = (IRequest) ctx.lookup("RequestBean/remote");			
			} catch (NamingException e) {			
				String error;
				error = "Error while lookup for RequestBean:\n"+e.getMessage();
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}
			UserBean user = (UserBean) session.getAttribute("user");
			if(user.isLogged()) {
				List<Order> orders =  req.getUserHistory(user.getUsername());
				Map<Integer, String> orderList = new HashMap<Integer, String>();				
				for(Order temp: orders) {
					orderList.put(temp.getOrderId(), temp.getDate().toString()+" ["+temp.getStatus().toString()+"]");
				}
				OrderList list = new OrderList();
				list.setOrderList(orderList);
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("historic.jsp");
				rd.forward(request, response);
			} else {
				String error;
				error = "You must be login.";
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}
			
		} else {
			//quer dizer que alguém andou a editar o link no browser 
			//error message
			String error;
			error = "Action not recognized.";
			List<String> errors = new ArrayList<String>();
			errors.add(error);
			ErrorList list = new ErrorList();
			list.setErrorList(errors);		
			request.setAttribute("list", list);
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);	
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Cart cart = (Cart)session.getAttribute("cart");
		UserBean user = (UserBean)session.getAttribute("user");
		if(user.isLogged()) {
			List<String> camerasList = cart.getCart();
			IPurchase purchase = null;
			IRequest req = null;
			InitialContext ctx = null;
			try {
				ctx = new InitialContext();
				purchase = (IPurchase) ctx.lookup("PurchaseBean/remote");
				req = (IRequest) ctx.lookup("RequestBean/remote");
			} catch (NamingException e) {			
				String error;
				error = "Error while lookup for PurchaseBean or RequestBean:\n"+e.getMessage();
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}						
			if(purchase.hasMoney()) {
				Order order = purchase.addOrderToDataBase(camerasList, user.getUsername());
				Cart cartBean = new Cart();
				session.setAttribute("cart", cartBean);
				OrderBean bean = new OrderBean();				
				bean.setCameras(camerasList);
				bean.setAmount(order.getAmount());
				bean.setDate(order.getDate().toString());
				bean.setId(order.getOrderId());
				User usr = order.getUser();
				bean.setAddress(usr.getAddress());
				bean.setName(usr.getFullName());
				bean.setStatus(order.getStatus().toString());
				bean.setUsername(usr.getUsername());
				request.setAttribute("order", bean);
				RequestDispatcher rd = request.getRequestDispatcher("order_details.jsp");
				rd.forward(request, response);	
			}else {
				//erro ao submeter order
				String error;
				error = "You don't have enough mooney.";
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);				
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}
		}
		else {
			String error;
			error = "You must be logged in.";
			List<String> errors = new ArrayList<String>();
			errors.add(error);
			ErrorList list = new ErrorList();
			list.setErrorList(errors);		
			request.setAttribute("list", list);
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);	
		}
	}

}
